package edu.sctu.renpingan.jsonpratice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Created by Administrator on 2015/6/23.
 */
public class JSon {
    public static final String URL = "http://api.ii.com.cn";
    public static final String PATH = URL+"/goods/apprec";
    GoodsInfo goodsInfo;

    /**
     *
     * 获得get得到信息并将它处理为字符串和可以调用的实体
     * @return
     * @throws IOException
     */
    public GoodsInfo getInfo() throws IOException {

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

        HttpGet httpGet = new HttpGet(PATH);


            HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
        if(entity != null) {
             goodsInfo = resolve00(EntityUtils.toString(entity));
            System.out.println("有值");
        }
        return goodsInfo;
        }

    /**
     * 快速解析
     * @param jsons
     * @return
     */
    public GoodsInfo resolve00(String jsons){
        GoodsInfo jsonObject = JSON.parseObject(jsons,  GoodsInfo.class);
        return jsonObject;
    }

    /**
     * 一般的正常解析
     * @param jSon
     * @return
     */
    public GoodsInfo resolve(String jSon ){
        GoodsInfo goods = null;
         GoodsInfo goodsInfo = new GoodsInfo();
        JSONObject object = JSON.parseObject(jSon);

        goodsInfo.count = (String) object.get("count");
        goodsInfo.error = object.getInteger("error");
        goodsInfo.message = object.getString("message");

        JSONArray array = (JSONArray) object.get("list");

        for (int i = 0; i < array.size(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
             goods = new GoodsInfo();
            GoodsAppbean goodsAppbean = new GoodsAppbean();

            goodsAppbean.brand_id = jsonObject.getString("brand_id");
            goodsAppbean.category_id = jsonObject.getString("category_id");
            goodsAppbean.goods_id = jsonObject.getString("goods_id");
            goodsAppbean.goods_price = jsonObject.getString("goods_price");
            goodsAppbean.red_id = jsonObject.getString("red_id");

            goods.list.add(goodsAppbean);
        }

        return  goods;
    }

}

